package bosc.cn.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tianshq
 * @date 2025/9/6 22:14
 * @description 外网用户WebSocket端点
 */
@Component
@ServerEndpoint(value = "/tunnel/user/{userId}")
@Slf4j
public class ExternalUserEndpoint {

    private static Map<String, Session> userSessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        userSessions.put(userId, session);
        log.info("外网用户连接成功: userId={}, sessionId={}", userId, session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId) {
        try {
            log.info("收到外网用户消息: userId={}, message={}", userId, message);
            // 消息格式: clientId|request_data
            String[] parts = message.split("\\|", 2);
            if (parts.length < 2) {
                session.getBasicRemote().sendText("ERROR: 消息格式不正确");
                return;
            }

            String clientId = parts[0];
            String requestData = parts[1];

            // 生成唯一请求ID
            String requestId = UUID.randomUUID().toString();

            // 注册请求会话
            InternalClientEndpoint.registerRequestSession(requestId, session);

            log.info("转发请求到内网客户端: userId={}, clientId={}, requestId={}", userId, clientId, requestId);
            // 转发请求到内网客户端
            boolean success = InternalClientEndpoint.forwardRequest(clientId, requestId, requestData);
            if (!success) {
                session.getBasicRemote().sendText("ERROR: 目标客户端未连接或转发失败");
                InternalClientEndpoint.registerRequestSession(requestId, null); // 清理
            }

        } catch (Exception e) {
            log.error("处理外网用户消息异常", e);
            try {
                session.getBasicRemote().sendText("ERROR: 处理请求异常 - " + e.getMessage());
            } catch (Exception ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        userSessions.remove(userId);
        log.info("外网用户断开连接: userId={}", userId);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") String userId) {
        log.error("外网用户连接异常: userId={}", userId, error);
        userSessions.remove(userId);
    }
}
